package com.aischool.admin;

import java.util.List;
import java.util.stream.Collectors;

import com.aischool.routes.RouteMapping;
import com.aischool.service.AiOrgService;
import com.aischool.service.SysAppService;
import com.aischool.service.SysPermissionService;
import com.aischool.utils.AppUtil;
import com.aischool.utils.DateUtil;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheKit;

@RouteMapping(url = "/admin")
public class AdminController extends Controller {
	
	@Inject
	SysAppService sysAppService;
	@Inject
	SysPermissionService sysPermissionService;
	@Inject
	AiOrgService aiOrgService;
	
	public void welcome() {
		
		render("welcome.html");
	}
	
	/**
	 * 登录 /admin/login/1
	 */
	public void login() {
		int app_id = getParaToInt(0, 0);
		if (app_id > 1) {
			this.redirect("/admin/eduorg/login/"+app_id);
			return;
		}else if (app_id == 1) {
			Record rd = sysAppService.getSysApp(app_id);
			if (rd != null) {
				this.setAttr("login_app_id", app_id);
				this.setAttr("login_app_name", rd.getStr("app_name"));
				render("login.html");
				return ;
			}
		}
		renderText("页面丢失！");
	}
	
	public void index() {
		int user_id = this.getAttrForInt("login_user_id");
		int app_id = this.getAttrForInt("login_app_id");
		int org_id = this.getAttr("login_org_id", 0);
		
		int url_app_id = getInt("app_id",0);
		if (url_app_id > 1) {
			this.redirect("/admin/eduorg/index?app_id="+url_app_id);
			return;
		}
		
		if (org_id > 0) {
			Record rd = aiOrgService.getOrg(org_id);
			System.err.println(rd);
			if (rd != null) {
				this.setAttr("index_org_name", rd.get("org_name"));
			}
		}
		
		if (app_id > 0 && user_id>0) {
			String url_welcome = "/admin/welcome";
			if (app_id == 4) {
				url_welcome = "/admin/eduorg/welcome";
			}
			this.setAttr("attr_welcome_url", url_welcome);
			
			List<Record> listmenu = sysPermissionService.getAppUserMenu(app_id, user_id);
			List<Record> listm1 = listmenu.stream()
					.filter((Record r) -> r.getInt("parent_id")==0)
					.collect(Collectors.toList());
			StringBuilder sb = new StringBuilder();
			for(int i = 0; i < listm1.size(); i++) {
				Record r1 = listm1.get(i);
				if (r1.getBoolean("is_hide")) {
					continue;
				}
				sb.append("<li class=\"layui-nav-item");
				//sb.append(" layui-nav-itemed");
				if (i==0) {
					sb.append(" layui-nav-itemed");
				}
				sb.append("\">");
				sb.append("<a href=\"javascript:;\"><i class=\"iconfont\">"+r1.getStr("icon_code")+"</i>"+r1.getStr("menu_name")+"</a>");
				List<Record> listm2 = listmenu.stream()
						.filter((Record r) -> r.getInt("parent_id")==r1.getInt("menu_id"))
						.collect(Collectors.toList());
				if (listm2 != null && listm2.size()>0) {
					sb.append("<dl class=\"layui-nav-child\">");
					for(int j=0; j < listm2.size(); j++) {
						Record r2 = listm2.get(j);
						if (r2.getBoolean("is_hide")) {
							continue;
						}
						sb.append("<dd><a href=\"javascript:;\" data-url=\""+AppUtil.addUrlParams(r2.getStr("menu_url"), "app_id="+app_id)+"\" "
								+ "data-id=\""+r2.getStr("menu_id")+"\" data-text=\""+r2.getStr("menu_name")+"\"><span class=\"l-line\"></span>"+r2.getStr("menu_name")+"</a></dd>");
					}
					sb.append("</dl>");
				}
				
				sb.append("</li>");
			}
			this.setAttr("listmenuhtml", sb.toString());
		}
		
		if (app_id > 0) {
			Record rd = sysAppService.getSysApp(app_id);
			if (rd != null) {
				this.setAttr("login_app_name", rd.getStr("app_name"));
				render("index.html");
				return ;
			}
		}
		renderText("页面丢失！");
	}
		
	public void list() {
		setParamsToAttr();
		String mname = getViewName();
		render(mname + "-list.html");
	}
	
	public void edit() {
		setParamsToAttr();
		String mname = getViewName();
		render(mname + "-edit.html");
	}
	
	/**
	 * 清空缓存
	 */
	public void clearcache() {
		//CacheKit.getCacheManager().clearAll();
		String[] arrNames = CacheKit.getCacheManager().getCacheNames();
		for(String sname : arrNames) {
			CacheKit.removeAll(sname);
			System.err.println("已清空：" + sname);
		}
		
		renderText("全部清除成功！"  + DateUtil.getCurrentDateStr());
	}
	
	private String getViewName() {
		String absUrl = getRequest().getRequestURI();
		String[] array1 = absUrl.split("/");
		String mname = array1[array1.length-1];
		return mname;
	}
	
	private void setParamsToAttr() {
		setAttr("ar_typeid", getPara("typeid",""));
		setAttr("ar_poid", getPara("poid",""));
	}
	

	
	public void gettables() {
		String sql = "";
		List<Record> listTable = Db.find("SELECT   tablename   FROM   pg_tables  \r\n" + 
				"WHERE   tablename   NOT   LIKE   'pg%'  \r\n" + 
				"AND tablename NOT LIKE 'sql_%'\r\n" + 
				"ORDER   BY   tablename;");
		for(int i=0;i<listTable.size();i++) {
			Record rdt = listTable.get(i);
			Record rdp = Db.findFirst("select pg_attribute.attname as colname,pg_type.typname as typename,pg_constraint.conname as pk_name from \r\n" + 
					"pg_constraint  inner join pg_class \r\n" + 
					"on pg_constraint.conrelid = pg_class.oid \r\n" + 
					"inner join pg_attribute on pg_attribute.attrelid = pg_class.oid \r\n" + 
					"and  pg_attribute.attnum = pg_constraint.conkey[1]\r\n" + 
					"inner join pg_type on pg_type.oid = pg_attribute.atttypid\r\n" + 
					"where pg_class.relname = '"+rdt.get("tablename")+"' \r\n" + 
					"and pg_constraint.contype='p'");
			if (rdp != null && rdp.getStr("typename").equals("int4")) {
				sql += "select setval('"+rdt.get("tablename")+"_"+rdp.get("colname")+"_seq', (select max("+rdp.get("colname")+") + 1 from "+rdt.get("tablename")+"));\r\n";
			}
		}
		renderText(sql);
	}
}
